﻿package src.game.managers{
	import src.game.Letter;
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	
	public class ObjectMover {
		private var animatedObjects:Vector.<Letter>;
		private var displayHolder:DisplayObjectContainer;
		
		public function ObjectMover(holder:DisplayObjectContainer) {
			animatedObjects = new Vector.<Letter>();
			this.displayHolder = holder;
		}
		
		public function update():void {
			for (var i:int = 0; i<animatedObjects.length; i++)
				animatedObjects[i].update();
		}
		
		public function add(object:Letter):void {
			animatedObjects.push(object);
			displayHolder.addChild(object);
			//displayHolder.setChildIndex(object, 1);
		}
		
		public function remove(object:Letter):void {
			var index:int = animatedObjects.indexOf(object);
			if (index >= 0) removeAt(index);
		}
		
		public function removeAt(index:int):void {
			displayHolder.removeChild(animatedObjects[index]);
			animatedObjects.splice(index, 1);
		}
		
		public function removeWithAnimation(index:int):void {
			animatedObjects[index].setRemove(true);
			animatedObjects[index].addEventListener(Event.CLEAR, removeHandler);
		}
		
		private function removeHandler(event:Event):void {
			event.target.removeEventListener(Event.CLEAR, removeHandler);
			remove((Letter)(event.target));
		}
		
		public function getObjectAt(index:int):Letter {
			return animatedObjects[index];
		}
		
		public function getObjectsNumber():int {
			return animatedObjects.length;
		}
		
		public function removeAll():void {
			for (var i:int = animatedObjects.length - 1; i>=0; i--) {
				displayHolder.removeChild(animatedObjects[i]);
			}
			animatedObjects.splice(0, animatedObjects.length);
		}
	}
	
}
